package fw.mvc;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fw.mvc.config.ConfigDoMap;
import fw.mvc.config.ConfigMap;

public class ActionServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		ServletContext context = req.getServletContext();
		
		String reqUrl = req.getServletPath();
		ConfigMap configMap = ConfigMap.getInstance();
		
		ConfigDoMap doConfig = configMap.get(reqUrl);
		
		try {
			IForm form = FormUtil.createForm(req, doConfig.getFormClass());
			
			String actionClassName = doConfig.getActionClass();
			Class actionClass = Class.forName(actionClassName);
			AbstractAction action = (AbstractAction)actionClass.newInstance();
			String condition = action.execute(req, resp, form);
			String renderer = doConfig.get(condition);
			
			req.getRequestDispatcher(renderer).forward(req, resp);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

	
}
